package com.qianfeng.yime.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.baidu.mapapi.model.LatLng;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.yime.CityChooseActivity;
import com.qianfeng.yime.Constants;
import com.qianfeng.yime.R;
import com.qianfeng.yime.adapter.SidelineListAdapter;
import com.qianfeng.yime.model.City;
import com.qianfeng.yime.model.Job;
import com.qianfeng.yime.model.User;
import com.qianfeng.yime.util.CommonUtils;
import com.qianfeng.yime.util.CurrentSingleton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;

/**
 * Created by Fcy on 2015/3/10.
 */
public class JianZhiFragment
        extends Fragment
        implements View.OnClickListener,
                    PullToRefreshBase.OnRefreshListener2<ListView> {

    /**
     * 兼职类型数组
     */
    private String[] itemsSideline = {"全部", "传单派发", "服务员", "促销员", "礼仪", "客服", "小时工", "其他"};
    /**
     * 查找范围选择数组
     */
    private String[] itemsRange = {"全部","1千米","3千米","5千米","10千米"};
    /**
     * 排序方式选择数组
     */
    private String[] itemsOrder = {"智能排序","发布时间","离我最近"};

    /**
     * 兼职数组选择
     */
    private int sidelineChosen = 0;
    /**
     * 查找范围选择
     */
    private int rangeChosen = 0;
    /**
     * 排序方式选择
     */
    private int ordChosen = 0;

    /**
     * 标志位，1为更新，2为加载
     */
    private int load = 1;
    /**
     * 设置加载第几页数据，默认加载第一页
     */
    private int pageNum = 1;//
    /**
     * 设置每页加载的数据条目数量，默认加载20条
     */
    private int pageSize = 20;//
    /**
     * 设置是否下载数据完成，，默认为false
     */
    private boolean isLoad = false;

    private TextView citySidelineCurrent;
    private TextView cityLocation;
    private LinkedList<Job> jobs;
    private SidelineListAdapter adapter;
    private City currentCity;
    private User user;
    private PullToRefreshListView cityList;

    private TextView sidelineChoose;
    private TextView rangeChoose;
    private TextView orderChoose;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View ret = inflater.inflate(R.layout.fragment_jianzhi, container, false);

        citySidelineCurrent = (TextView) ret.findViewById(R.id.text_sideline_current_city);
        LinearLayout cityCurrent = (LinearLayout) ret.findViewById(R.id.layout_city_choose);
        LinearLayout sidelineType = (LinearLayout) ret.findViewById(R.id.layout_sideline_type_choose);
        LinearLayout rangeType = (LinearLayout) ret.findViewById(R.id.layout_range_choose);
        LinearLayout orderType = (LinearLayout) ret.findViewById(R.id.layout_order_choose);
        cityLocation = (TextView) ret.findViewById(R.id.text_location_city);
        ImageView cityLocationRefresh = (ImageView) ret.findViewById(R.id.img_city_refresh);
        cityList = (PullToRefreshListView) ret.findViewById(R.id.list_refresh_sideline);

        sidelineChoose = (TextView) ret.findViewById(R.id.text_sideline_type_chosen);
        rangeChoose = (TextView) ret.findViewById(R.id.text_range_chosen);
        orderChoose = (TextView) ret.findViewById(R.id.text_order_chosen);

        cityList.setMode(PullToRefreshBase.Mode.BOTH);

        initSidelineCurrentCity();//初始化当前城市

        ListView refreshableView = cityList.getRefreshableView();

        registerForContextMenu(refreshableView);

        jobs = new LinkedList<Job>();
        adapter = new SidelineListAdapter(getActivity(), jobs);
        refreshableView.setAdapter(adapter);

        initJobsList();//初始化招聘列表

        cityList.setOnRefreshListener(this);

        cityCurrent.setOnClickListener(this);//当前城市选择按钮
        sidelineType.setOnClickListener(this);//兼职类型选择按钮
        rangeType.setOnClickListener(this);//范围选择按钮
        orderType.setOnClickListener(this);//排序方式选择按钮
        cityLocationRefresh.setOnClickListener(this);//刷新当前定位城市接口

        return ret;
    }

    @Override
    public void onResume() {
        super.onResume();
        initSidelineCurrentCity();
        initJobsList();
    }

    /**
     * 初始化招聘列表
     */
    private void initJobsList() {
        HttpUtils httpUtils = new HttpUtils();
        int userId = 0;
        if (user != null) {
            userId = user.getId();
        }
        if (currentCity != null) {
            int id = currentCity.getId();
            LatLng latLng = currentCity.getLatLng();

            double latitude;
            final double longitude;
            String url = null;

            if (latLng != null) {
                latitude = latLng.latitude;
                longitude = latLng.longitude;
                url = Constants.SIDELINE_LIST +
                        "?cityId=" + id +
                        "&lat=" + latitude +
                        "&lon=" + longitude +
                        "&pageNum=" + pageNum +
                        "&pageSize=" + pageSize +
                        "&jobTypeId=" + sidelineChosen +
                        "&km=" + rangeChosen +
                        "&sort=" + ordChosen;
            }else {
                url = Constants.SIDELINE_LIST +
                        "?cityId=" + id +
                        "&pageNum=" + pageNum +
                        "&pageSize=" + pageSize +
                        "&jobTypeId=" + sidelineChosen +
                        "&km=" + rangeChosen +
                        "&sort=" + ordChosen;
            }
            httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    String result = responseInfo.result;
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200){
                            JSONObject data = jsonObject.getJSONObject("data");
                            JSONArray listArray = data.getJSONArray("list");
                            LinkedList<Job> list = new LinkedList<Job>();
                            for (int i = 0; i < listArray.length(); i++) {
                                JSONObject jobObject = listArray.getJSONObject(i);
                                Job job = new Job();
                                job.parseJson(jobObject);
                                list.add(job);
                            }
                            if (load == 1){
                                jobs.clear();
                                jobs.addAll(list);
                            }else if (load == 2){
                                jobs.addAll(list);
                            }
                            isLoad = true;
                            cityList.onRefreshComplete();
                            adapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(HttpException error, String msg) {
                    System.out.println("msg = " + msg);
                    CommonUtils.toast(getActivity(), "招聘列表获取失败");
                }
            });
        }else {
            CommonUtils.toast(getActivity(), "当前未确定城市");
        }
    }

    /**
     * 初始化当前城市
     */
    private void initSidelineCurrentCity() {
        CurrentSingleton singleton = CurrentSingleton.getInstance();
        currentCity = singleton.getCurrentCity();
        user = singleton.getUser();
        if (currentCity != null) {
            String name = currentCity.getName();
            citySidelineCurrent.setText(name);
        }
    }

    /**
     * 按钮点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.layout_city_choose:
                //TODO 城市选择按钮
                Intent intent = new Intent(getActivity(), CityChooseActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_sideline_type_choose:
                //TODO 招聘类型选择按钮
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("招聘类型").setItems(itemsSideline, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sidelineChosen = which;
                    }
                }).create().show();
                break;
            case R.id.layout_range_choose://
                //TODO 范围选择按钮
                builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("查找范围").setItems(itemsRange, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        rangeChosen = which;
                    }
                }).create().show();
                break;
            case R.id.layout_order_choose:
                //TODO 排序类型选择按钮
                builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("排序方式").setItems(itemsOrder, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ordChosen = which;
                    }
                }).create().show();
                break;
            case R.id.img_city_refresh:
                //TODO 刷新当前定位城市按钮
                cityLocation.setText("北京");
                break;
        }
        initChosen();
    }

    /**
     * 初始化选择按钮
     */
    private void initChosen() {
        sidelineChoose.setText(itemsSideline[sidelineChosen]);
        rangeChoose.setText(itemsRange[rangeChosen]);
        orderChoose.setText(itemsOrder[ordChosen]);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        load = 1;
        initJobsList();
//        if (isLoad){
//            refreshView.onRefreshComplete();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        load = 2;
        pageNum++;
        initJobsList();
    }
}